<template>
  <div class="pageContent">
    <div class="centerAll ">
      <div class="content">
        <div class="title">新增问诊单</div>
        <div class="top">
          <div><el-input v-model="formData.name" placeholder="请输入问诊单名称" style="width: 240px;"></el-input></div>
          <div class="buttonAll">
            <el-button type="primary" @click="dialogOpen(1)">导入已有问诊单</el-button>
            <el-button type="primary" @click="dialogOpen(2)">添加单选题</el-button>
            <el-button type="primary" @click="dialogOpen(3)">添加多选题</el-button>
            <el-button type="primary" @click="dialogOpen(4)">添加问答题</el-button>
            <el-button type="warning" @click="dialogOpen(5)">清除</el-button>
          </div>
        </div>
        <div class="allItxst">
          <div class="itxst">
            <draggable :list="dragQuestion.list" ghost-class="ghost" chosen-class="chosenClass" animation="300"
              @start="onStart" @end="onEnd" axis="x" class="allDrag" scroll-speed="20">
              <template #item="{ element }">
                <div class="item" :class="element.type === 1 ? 'radio-bg' : 'checkbox-bg'">
                  <img v-if="element.type === 1" src="https://images.dayiketang.com/draggable/radio.png" alt="" class="aqb-lb-img absolute" draggable="false">
                  <img v-else-if="element.type === 2" src="https://images.dayiketang.com/draggable/checkbox.png" alt="" class="aqb-lb-img absolute" draggable="false">
                  <img v-else-if="element.type === 3" src="https://images.dayiketang.com/draggable/questionnaire.png" alt="" class="aqb-lb-img absolute" draggable="false">
                  <div style="width: 100%;">
                    <div class="dragImg">
                      <img src="https://images.dayiketang.com/draggable/draggable.png" alt="">
                      <img src="https://images.dayiketang.com/draggable/edit.png" alt="">
                      <img src="https://images.dayiketang.com/draggable/del.png" @click="deleteItem(element)" alt="">
                    </div>
                    <div> {{ element.title }}</div>
                    <el-radio-group v-if="element.type === 1" v-model="dragForm[element.id]">
                      <el-radio v-for="(r, rk) in element.options" :key="rk" :label="r.title" :value="r.id"></el-radio>
                    </el-radio-group>
                    <el-checkbox-group v-if="element.type === 2" v-model="dragForm[element.id]">
                      <el-checkbox v-for="(r, rk) in element.options" :key="rk" :label="r.title" :value="r.id"></el-checkbox>
                    </el-checkbox-group>
                    <el-input type="textarea" v-if="element.type === 3"></el-input>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </div>
      </div>

      <div class="content">
        <div class="title">问诊单设置</div>
        <el-form :model="form" label-width="auto" class="formAll">
          <el-form-item label="使用医生:">
            <div>
              <el-radio-group v-model="formData.scope" class="ml-4">
                <el-radio :value="0" size="large">全部医生</el-radio>
                <el-radio :value="1" size="large">指定医生</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <div v-if="formData.scope === 1" class="doctorAll">
            <div class="addDoctor" v-for="(item,index) in doctor.list" :key="index">
              <img src="/src/assets/closeW.png" class="close" @click="doctor.delete(index)" alt="">
              <el-avatar :src="item.url" />
              <div class="doctorName">{{item.name}}</div>
            </div>
            <div class="qsb-db-add" @click="openDoctorDialog">
              <img src="https://images.dayiketang.com/add@3x.png" alt="" class="qsb-db-a-img mt-18 mb-8">
              <div class="qsb-db-a-desc font-14">添加指定医生</div>
            </div>
          </div>
        </el-form>
      </div>


      <div class="bottomBtn">
        <el-button @click="back">返回</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="700px">
    <div v-if="dialog === 1">
      <div>
        <el-input v-model="inquiry.keyword" placeholder="请输入问诊单名称" style="width: 260px;margin-right: 20px;"></el-input>
        <el-button type="primary" @click="inquiry.filter()">筛选</el-button>
      </div>
      <div>
        <el-radio-group v-model="inquiry.sel" class="dialog">
          <el-radio v-for="(item, index) in inquiry.list" :label="item.name">{{item.name}} </el-radio>
        </el-radio-group>
      </div>
    </div>

    <div v-if="[2,3,4].includes(dialog)">
      <el-tabs v-model="activeNameDialog" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="dialog === 2 ? '单选题库' : (dialog === 3 ? '多选题库' : '问答题库')" :name="1">
          <div>
            <el-input v-model="questionsName" placeholder="请输入问题名称" style="width: 260px;margin-right: 20px;"></el-input>
            <el-button type="primary" @click="getQuestions(questionType, questionsName)">筛选</el-button>
          </div>

          <el-checkbox-group v-model="questionSelIds" @change="handleCheckedCitiesChange" class="dialog">
            <el-checkbox v-for="(q, qk) in questionOptions" :key="qk" :label="q.title" :value="q.id">
              {{ q.title }}
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
        <el-tab-pane :label="dialog === 2 ? '新增单选题' : (dialog === 3 ? '新增多选题' : '新增问答题')" :name="2">
          <Form ref="xrForm"
                :table-column="questionFormColumn"
                :form-data="questionForm"
                :is-read="false"
                @update-options="updateOptions" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeQuesDialog">取消</el-button>
        <el-button type="primary" @click="addQuestion">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加医生 -->
  <AddDoctorDialog ref="doctorDialogRef" @addDoctorForParent="doctor.add"></AddDoctorDialog>

</template>

<script setup>
import AddDoctorDialog from "./components/AddDoctorDialog.vue"
import { search as questionSearch } from "@/api/inquiry/question"
import { create, search } from "@/api/inquiry/list"
import { create as questionSave } from '/src/api/inquiry/question'
import { reactive, ref, nextTick } from "vue";
import draggable from "vuedraggable";
import { ElMessage, ElMessageBox } from 'element-plus'
import Form from "@/components/Form/index.vue";
import { radioFormColumn, checkboxFormColumn, textFormColumn } from '../questionBank/config'
const questionForm = ref({})
const questionFormColumn = ref()
const xrForm = ref()
const formData = reactive({
  name: "",
  scope: 0
})
const dialog = ref(null)
const dialogFormVisible = ref(false)
const dialogTitle = ref('')
const activeNameDialog = ref(1)
const formRef = ref(null)
const doctorDialogRef = ref()
const dynamicValidateForm = ref({
  subject2: [{
    title: ''
  }]
})
// 问诊单
const inquiry = reactive({
  sel: [],
  list: [],
  keyword: "",
  filter: async () => {
    const res = await search({
      name: inquiry.keyword
    })
    inquiry.list = res.data
  }
})
// 医生
const doctor = reactive({
  list: [],
  selIds: [],
  delete: (doctorIndex) => {
    doctor.list.splice(doctorIndex, 1);
    doctor.selIds.splice(doctorIndex, 1);
  },
  add: (selList, selIds) => {
    doctor.list.concat(selList)
    doctor.selIds.concat(selIds)
  }
})
const questionOptions = ref([])
const questionsName = ref()
const questionType = ref()
const questionSelIds = ref([])

const updateOptions = (f, index) => {
  if (index) {
    questionForm.value[f.prop].splice(index, 1)
  } else {
    questionForm.value[f.prop].push({ "id": 0, "title": "" })
  }
}

// 问题添加到编辑区域
const addQuestion = async () => {
  if (activeNameDialog.value === 2) {
    const res = await submitQuestionForm()
    if (res?.code !== 200) { return }

    const _questionOptions = {...questionForm.value, type: dialog.value - 1 }
    console.log(_questionOptions)
    _questionOptions.options = _questionOptions.options.map(item => {
      return { id: new Date().getTime(), title: item.title }
    })
    console.log("_questionOptions", _questionOptions)
    dragQuestion.list.push(_questionOptions)
  } else {
    for (const question of questionOptions.value) {
      if (questionSelIds.value.includes(question.id)) {
        dragQuestion.list.push(question)
      }
    }
  }
  dialogFormVisible.value = false
}

const submitQuestionForm = async () => {
  return new Promise(async resolve => {
    if (!xrForm.value.ruleFormRef) return
    await xrForm.value.ruleFormRef.validate(async (valid, fields) => {
      if (valid) {
        const options = { ...questionForm.value }
        options.type = questionType.value
        if (options.options) {
          options.options = options.options.map(item=>item.title)
        }
        const res = await questionSave(options);
        console.log(res)
        resolve(res)
      } else {
        console.log('error submit!', fields)
      }
    })
  })

}

const back = ()=> {
  router.go(-1)
}


const openDoctorDialog = () => {
  doctorDialogRef.value.openDialog()
}
const deleteForm = (formItem) => {
  dynamicValidateForm.value.subject2 = dynamicValidateForm.value.subject2.filter(
    (item, index) => {
      return index !== formItem;
    }
  );
}

const getQuestions = async(type, keyword) => {
  console.log(11)
  const res = await questionSearch({
    type,
    title: keyword
  })
  questionOptions.value = res.data
}

const closeQuesDialog = () => {
  dialogFormVisible.value = false
}

const dialogOpen = async (type) => {
  if ([2, 3, 4].includes(type)) {
    questionType.value = type - 1
    await getQuestions(questionType.value)
  }
  if (type !== 5) {
    if (type === 1) {
      dialog.value = 1
      dialogTitle.value = "搜索问诊单"
    } else if (type === 2) {
      dialog.value = 2
      dialogTitle.value = ""
      questionFormColumn.value = radioFormColumn
    } else if (type === 3) {
      dialog.value = 3
      dialogTitle.value = ""
      questionFormColumn.value = checkboxFormColumn
    } else if (type === 4) {
      dialog.value = 4
      dialogTitle.value = ""
      questionFormColumn.value = textFormColumn
    }
    dialogFormVisible.value = true
    await nextTick(() => {
      questionForm.value = {
        options: [{"id": 0, "title": ""},]
      }
      xrForm.value.ruleFormRef.resetFields()
      xrForm.value.ruleFormRef.clearValidate()
    })
  } else {
    ElMessageBox.confirm(
        '确定清空吗？?',
        '警告提示', {
          confirmButtonText: '继续执行',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      .then(() => {
        dragQuestion.list = []
      })
      .catch(() => {
        ElMessage({
          type: 'info',
            message: 'Delete canceled',
          })
        })
    }
  }

//多选
const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedCities = ref(['Shanghai', 'Beijing'])
const cities = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen']

const handleCheckAllChange = (val) => {
  checkedCities.value = val ? cities : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === cities.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.length
}

const submitForm = async () => {
  const options = { ...formData }
  options.question = dragQuestion.list.map(item=> {
    return { id: item.id }
  })
  await create(options);
  ElMessage.success("创建成功");
  setTimeout(() => {
    back()
  }, 1000)
}

  //拖拽
  const dragForm = reactive({})
  const dragQuestion = reactive({
    list: [{
      "id": 9,
      "title": "大便如何",
      "type": 2,
      "options": [
        {
          "id": 14,
          "title": "可以"
        },
        {
          "id": 15,
          "title": "便秘"
        }
      ]
    },
      {
        "id": 11,
        "title": "感觉怎么样？",
        "type": 3,
        "options": []
      },{
        "id": 18,
        "title": "夜梦盗汗？",
        "type": 1,
        "options": [
          {
            "id": 28,
            "title": "是"
          },
          {
            "id": 29,
            "title": "否"
          }
        ]
      }],
  })

  //拖拽开始的事件
  const onStart = () => {
    console.log("开始拖拽");
  };

  //拖拽结束的事件
  const onEnd = () => {
    console.log("结束拖拽");
  };
  const deleteItem = (element) => {
    console.log("删除项目：" + element.name);

    dragQuestion.list = dragQuestion.list.filter(
      (item) => {
        return item.id !== element.id;
      }
    );
  }
</script>

<style lang="scss" scoped>
  .aqb-lb-img {
    width: 54px;
    height: 54px;
    top: 0;
    left: 0;
  }
  .title {
    border-left: 4px solid #1890ff;
    font-size: 16px;
    padding-left: 12px;
  }

  .content {
    margin-bottom: 20px;
  }

  .top {
    margin: 20px 0 0 0;
    display: flex;
    justify-content: space-between;
  }

  .top .buttonAll ::v-deep .el-button {
    margin-bottom: 10px;
    margin-left: 0px !important;
    margin-right: 6px;
  }

  ::v-deep .el-input__inner::-webkit-input-placeholder {
    color: #b6bcc4;
    font-size: 14px;
  }

  ::v-deep .el-form-item__label-wrap {
    display: flex;
    align-items: center;
  }

  ::v-deep .el-textarea__inner::-webkit-input-placeholder {
    color: #b6bcc4;
    font-size: 14px;
  }

  .dialog {
    display: flex;
    flex-flow: column nowrap;
    align-items: flex-start;
  }

  .dialog ::v-deep .el-dialog__header {
    border-bottom: 1px solid #f4f4f5;
    margin-bottom: 20px;
  }

  .dialog ::v-deep .el-radio {
    padding: 30px 0;
    border-bottom: 1px solid #f4f4f5;
    width: 100%;
  }

  .dialog ::v-deep .el-radio__input.is-checked .el-radio__inner {
    box-shadow: #f4f4f5;
  }

  .dialog ::v-deep .el-checkbox {
    padding: 30px 0;
    border-bottom: 1px solid #f4f4f5;
    width: 100%;
  }

  .checkAll ::v-deep .el-checkbox {
    padding: 30px 0;
    border-bottom: 1px solid #f4f4f5;
    width: 100%;
  }

  .formAll {
    width: 100%;
    padding: 20px 40px;
  }

  .doctorAll {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;


    .addDoctor {
      width: 100px;
      height: 80px;
      border-radius: 4px;
      background: #d8ebf3;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      position: relative;
      margin: 0 10px;

      .doctorName {
        color: #606266;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        width: 92%;
        font-size: 14px;
        margin-top: 10px;
      }

      .close {
        width: 20px;
        height: 20px;
        position: absolute;
        top: 4px;
        right: 4px;
      }

    }
  }
  .qsb-db-add {
    width: 110px;
    height: 80px;
    border-radius: 5px;
    background: rgba(24, 144, 255, 0.05);
    text-align: center;
    cursor: pointer;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    .qsb-db-a-img {
      width: 22px;
      height: 22px;
      vertical-align: top;
      display: block;
    }
    .qsb-db-a-desc {
      width: 100%;
      height: 20px;
      line-height: 20px;
      color: #1890ff;
    }
  }

  .demo-dynamic {
    width: 80%;
    margin: 0 auto;
  }

  .formClose {
    width: 20px;
    height: 20px;
    margin-left: 4px;
    margin-bottom: 10px;
  }

  .dynamicValidateForm {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin: auto 0;
  }

  .dynamicValidateForm ::v-deep .el-form-item {
    margin-bottom: 0px;
    height: 60px;
    padding-bottom: 10px;
    width: 92%;
  }

  .allItxst {
    max-height: 400px;
  }

  .allItxst::-webkit-scrollbar {
    width: 0;
    /* 隐藏滚动条的宽度 */
  }
  .pageContent::-webkit-scrollbar {
    width: 0;
    /* 隐藏滚动条的宽度 */
  }

  .itxst {
    // width: 200px;
    display: flex;
    flex-direction: row;


  }

   //拖拽区域
  .allDrag {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    cursor: pointer;

    .item {
      position: relative;
      width: 260px;
      background: olive;
      text-align: left;
      border-radius: 4px;
      padding: 10px 20px 20px 20px;
      display: flex;
      flex-direction: row;
      background: palevioletred;
      margin: 10px 10px;
      &.radio-bg {
        background: rgba(31, 219, 177, 0.05);
      }
      &.checkbox-bg {
        background: rgba(24, 144, 255, 0.05);
      }
    }
    .item:hover {
      cursor: pointer;
      border: none !important;
    }
  }



  // .item+.item {
  //   margin-top: 10px;
  // }

  .ghost {
    border: solid 1px rgb(19, 41, 239);
  }

  .chosenClass {
    background: palevioletred;
  }

  .dragImg {
    display: flex;
    justify-content: flex-end;

    img {
      width: 18px;
      height: 18px;
      margin: 0 4px;
    }
  }
</style>
